package info.xinfu.carban.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.daniulive.smartplayer.SmartPlayerJniV2;
import com.eventhandle.NTSmartEventCallbackV2;
import com.eventhandle.NTSmartEventID;
import com.videoengine.NTUserDataCallback;

import org.easydarwin.video.EasyPlayerClient;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.nio.ByteBuffer;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.xinfu.carban.BuildConfig;
import info.xinfu.carban.R;
import info.xinfu.carban.base.BaseFragment;
import info.xinfu.carban.event.Event_Play_Camera;
import info.xinfu.carban.myview.VideoViewController;
import info.xinfu.carban.utils.SPUtils;

import static org.greenrobot.eventbus.EventBus.getDefault;

public class BanFeeEntryragment extends BaseFragment {

    @BindView(R.id.surfaceVideo)
    SurfaceView sSurfaceView;

    Unbinder unbinder;
    @BindView(R.id.btn_start_play)
    Button btnStartPlay;
    @BindView(R.id.texture_view)
    TextureView mVideoView;


    private long playerHandle = 0;

    private static final int PLAYER_EVENT_MSG = 1;
    private static final int PLAYER_USER_DATA_MSG = 2;
    private static final int PLAYER_SEI_DATA_MSG = 3;

    private static final int PORTRAIT = 1; // 竖屏
    private static final int LANDSCAPE = 2; // 横屏
    private static final String TAG = "SmartPlayer";

    private SmartPlayerJniV2 libPlayer = null;

    private int currentOrigentation = PORTRAIT;

    private String playbackUrl = null;

    private boolean isMute = false;

    private boolean isHardwareDecoder = false;

    private int playBuffer = 200; // 默认200ms

    private boolean isLowLatency = false; // 超低延时，默认不开启

    private boolean isFastStartup = true; // 是否秒开, 默认true

    private int rotate_degrees = 0;

    private boolean switchUrlFlag = false;

    private boolean is_flip_vertical = false;

    private boolean is_flip_horizontal = false;

    private String switchURL = "rtmp://live.hkstv.hk.lxdns.com/live/hks";

    private String imageSavePath;

    private String recDir = "/sdcard/daniulive/playrec"; // for recorder path

    private boolean isPlaying = false;
    private boolean isRecording = false;
    private String mType;
    private Context myContext;
    private VideoViewController con;
    LinearLayout lLayout = null;
    FrameLayout fFrameLayout = null;
    EasyPlayerClient easyPlayerClient;

    static {
        System.loadLibrary("SmartPlayer");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static BanFeeEntryragment getInstance(String type) {
        BanFeeEntryragment fragment1 = new BanFeeEntryragment();
        Bundle bdl = new Bundle();
        bdl.putString("type", type);
        fragment1.setArguments(bdl);
        return fragment1;
    }

    @Override
    protected void initListener() {

    }


    @Override
    protected void initView() {
        getDefault().register(this);
        mType = getArguments().getString("type");
        libPlayer = new SmartPlayerJniV2();
        myContext = context.getApplicationContext();
        easyPlayerClient = new EasyPlayerClient(context, BuildConfig.KEY, mVideoView, null, null);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getRootViewId() {
        return R.layout.fragment_fee_entry;
    }


    private void InitAndSetConfig(String playbackUrl) {
        playerHandle = libPlayer.SmartPlayerOpen(myContext);

        if (playerHandle == 0) {
            Log.e(TAG, "surfaceHandle with nil..");
            return;
        }

        libPlayer.SetSmartPlayerEventCallbackV2(playerHandle,
                new EventHandeV2());

        libPlayer.SmartPlayerSetBuffer(playerHandle, playBuffer);

        // set report download speed(默认5秒一次回调 用户可自行调整report间隔)
        libPlayer.SmartPlayerSetReportDownloadSpeed(playerHandle, 1, 5);

        libPlayer.SmartPlayerSetFastStartup(playerHandle, isFastStartup ? 1 : 0);

        //设置RTSP超时时间
        int rtsp_timeout = 10;
        libPlayer.SmartPlayerSetRTSPTimeout(playerHandle, rtsp_timeout);

        //设置RTSP TCP/UDP模式自动切换
        int is_auto_switch_tcp_udp = 1;
        libPlayer.SmartPlayerSetRTSPAutoSwitchTcpUdp(playerHandle, is_auto_switch_tcp_udp);

        libPlayer.SmartPlayerSaveImageFlag(playerHandle, 1);

        // It only used when playback RTSP stream..
        // libPlayer.SmartPlayerSetRTSPTcpMode(playerHandle, 1);

//        playbackUrl = "rtsp://192.168.1.56/stream1";

        //  playbackUrl = "rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov";

        //playbackUrl = "rtmp://player.daniulive.com:1935/hls/stream1";

        // playbackUrl =
        // "rtsp://218.204.223.237:554/live/1/67A7572844E51A64/f68g2mj7wjua3la7";

        // playbackUrl =
        // "rtsp://rtsp-v3-spbtv.msk.spbtv.com/spbtv_v3_1/214_110.sdp";

        if (playbackUrl == null) {
            Log.e(TAG, "playback URL with NULL...");
            return;
        }

        libPlayer.SmartPlayerSetUrl(playerHandle, playbackUrl);
    }

   /* @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(Event_Car_Info event) {
        if (!TextUtils.isEmpty(event.getMsg())) {
            tvEntryTime.setText(event.getMsg());
        }
    }*/

    @OnClick(R.id.btn_start_play)
    public void onViewClicked() {
        if (true) {
     /*       String url="rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov";
//            con.start(url);
            Toast.makeText(context, "点击了按钮", Toast.LENGTH_LONG).show();

            con.start(url);*/
//rtsp://IP/stream1
          /*  EasyPlayerClient client = new EasyPlayerClient(context, BuildConfig.KEY, mVideoView, null, null);
            String url = "rtsp://" + ipAddress.getText().toString() + "/stream1";
            if (!TextUtils.isEmpty(url)) {
                client.play(url);
            } else {
                client.play(BuildConfig.RTSP_URL);
            }*/

        } else {

            if (!isRecording) {
                InitAndSetConfig("");
            }

            libPlayer.SmartPlayerSetSurface(playerHandle, sSurfaceView);


            Log.i(TAG, "Start playback stream++");

            // 如果第二个参数设置为null，则播放纯音频
            libPlayer.SmartPlayerSetSurface(playerHandle, sSurfaceView);
            // External Render test
            // libPlayer.SmartPlayerSetExternalRender(playerHandle, new
            // RGBAExternalRender());
            // libPlayer.SmartPlayerSetExternalRender(playerHandle, new
            // I420ExternalRender());

            libPlayer.SmartPlayerSetUserDataCallback(playerHandle, new UserDataCallback());
            //libPlayer.SmartPlayerSetSEIDataCallback(playerHandle, new SEIDataCallback());

            libPlayer.SmartPlayerSetAudioOutputType(playerHandle, 0);

            if (isMute) {
                libPlayer.SmartPlayerSetMute(playerHandle, isMute ? 1
                        : 0);
            }

            if (isHardwareDecoder) {
                Log.i(TAG, "check isHardwareDecoder: "
                        + isHardwareDecoder);

                int hwChecking = libPlayer
                        .SetSmartPlayerVideoHWDecoder(playerHandle,
                                isHardwareDecoder ? 1 : 0);

                Log.i(TAG, "[daniulive] hwChecking: " + hwChecking);
            }

            libPlayer.SmartPlayerSetLowLatencyMode(playerHandle, isLowLatency ? 1
                    : 0);

            libPlayer.SmartPlayerSetFlipVertical(playerHandle, is_flip_vertical ? 1 : 0);

            libPlayer.SmartPlayerSetFlipHorizontal(playerHandle, is_flip_horizontal ? 1 : 0);

            libPlayer.SmartPlayerSetRotation(playerHandle, rotate_degrees);

            int iPlaybackRet = libPlayer
                    .SmartPlayerStartPlay(playerHandle);

            if (iPlaybackRet != 0) {
                Log.e(TAG, "StartPlayback strem failed..");
                return;
            }

            isPlaying = true;
            Log.i(TAG, "Start playback stream--");
        }

    }


    class EventHandeV2 implements NTSmartEventCallbackV2 {
        @Override
        public void onNTSmartEventCallbackV2(long handle, int id, long param1,
                                             long param2, String param3, String param4, Object param5) {

            //Log.i(TAG, "EventHandeV2: handle=" + handle + " id:" + id);

            String player_event = "";

            switch (id) {
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_STARTED:
                    player_event = "开始..";
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_CONNECTING:
                    player_event = "连接中..";
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_CONNECTION_FAILED:
                    player_event = "连接失败..";
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_CONNECTED:
                    player_event = "连接成功..";
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_DISCONNECTED:
                    player_event = "连接断开..";
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_STOP:
                    player_event = "停止播放..";
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_RESOLUTION_INFO:
                    player_event = "分辨率信息: width: " + param1 + ", height: " + param2;
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_NO_MEDIADATA_RECEIVED:
                    player_event = "收不到媒体数据，可能是url错误..";
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_SWITCH_URL:
                    player_event = "切换播放URL..";
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_CAPTURE_IMAGE:
                    player_event = "快照: " + param1 + " 路径：" + param3;

                    if (param1 == 0) {
                        player_event = player_event + ", 截取快照成功";
                    } else {
                        player_event = player_event + ", 截取快照失败";
                    }
                    break;

                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_RECORDER_START_NEW_FILE:
                    player_event = "[record]开始一个新的录像文件 : " + param3;
                    break;
                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_ONE_RECORDER_FILE_FINISHED:
                    player_event = "[record]已生成一个录像文件 : " + param3;
                    break;

                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_START_BUFFERING:
                    Log.i(TAG, "Start Buffering");
                    break;

                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_BUFFERING:
                    Log.i(TAG, "Buffering:" + param1 + "%");
                    break;

                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_STOP_BUFFERING:
                    Log.i(TAG, "Stop Buffering");
                    break;

                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_DOWNLOAD_SPEED:
                    player_event = "download_speed:" + param1 + "Byte/s" + ", "
                            + (param1 * 8 / 1000) + "kbps" + ", " + (param1 / 1024)
                            + "KB/s";
                    break;

                case NTSmartEventID.EVENT_DANIULIVE_ERC_PLAYER_RTSP_STATUS_CODE:
                    Log.e(TAG, "RTSP error code received, please make sure username/password is correct, error code:" + param1);
                    player_event = "RTSP error code:" + param1;
                    break;
            }

            if (player_event.length() > 0) {
                Log.i(TAG, player_event);
                Message message = new Message();
                message.what = PLAYER_EVENT_MSG;
                message.obj = player_event;
                handler.sendMessage(message);
            }
        }
    }

    class UserDataCallback implements NTUserDataCallback {
        private int user_data_buffer_size = 0;

        private ByteBuffer user_data_buffer_ = null;

        private static final int NT_SDK_E_H264_SEI_USER_DATA_TYPE_BYTE_DATA = 1;
        private static final int NT_SDK_E_H264_SEI_USER_DATA_TYPE_UTF8_STRING = 2;

        @Override
        public ByteBuffer getUserDataByteBuffer(int size) {
            if (size < 1) {
                return null;
            }

            if (size <= user_data_buffer_size && user_data_buffer_ != null) {
                return user_data_buffer_;
            }

            user_data_buffer_size = size + 512;
            user_data_buffer_ = ByteBuffer.allocateDirect(user_data_buffer_size);

            return user_data_buffer_;
        }

        private String byteArrayToStr(byte[] byteArray) {
            if (byteArray == null) {
                return null;
            }
            String str = new String(byteArray);
            return str;
        }

        @Override
        public void onUserDataCallback(int ret, int data_type, int size, long timestamp, long reserve1, long reserve2) {
            //Log.i("onUserDataCallback", "ret: " + ret + ", data_type: " + data_type + ", size: " + size + ", timestamp: "+ timestamp);
            if (data_type == NT_SDK_E_H264_SEI_USER_DATA_TYPE_UTF8_STRING) {
                if (user_data_buffer_ == null)
                    return;

                user_data_buffer_.rewind();

                byte[] byte_buffer = new byte[size];
                user_data_buffer_.get(byte_buffer);

                String str = byteArrayToStr(byte_buffer);

                Log.i(TAG, "onUserDataCallback, userdata: " + str);

                Message message = new Message();
                message.what = PLAYER_USER_DATA_MSG;
                message.obj = str;
                handler.sendMessage(message);
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case PLAYER_EVENT_MSG:
                    String cur_event = "Event: " + (String) msg.obj;
//                    txtEventMsg.setText(cur_event);
                    break;
                case PLAYER_USER_DATA_MSG:
                    String user_data = "收到信息: " + (String) msg.obj;
//                    txtUserDataMsg.setText(user_data);
                    break;
                default:
                    break;
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(Event_Play_Camera event) {
        if (event.isRefresh()) {

            String url;
            if (mType.equals("entry")) {
                url = "rtsp://" + SPUtils.getString("ipentry", "") + "/stream1";
            } else {

                url = "rtsp://" + SPUtils.getString("ipexit", "") + "/stream1";
            }

            if (!TextUtils.isEmpty(url)) {

                if (!isRecording) {
                    InitAndSetConfig(url);
                }

                libPlayer.SmartPlayerSetSurface(playerHandle, sSurfaceView);


                Log.i(TAG, "Start playback stream++");

                // 如果第二个参数设置为null，则播放纯音频
                libPlayer.SmartPlayerSetSurface(playerHandle, sSurfaceView);
                // External Render test
                // libPlayer.SmartPlayerSetExternalRender(playerHandle, new
                // RGBAExternalRender());
                // libPlayer.SmartPlayerSetExternalRender(playerHandle, new
                // I420ExternalRender());

                libPlayer.SmartPlayerSetUserDataCallback(playerHandle, new UserDataCallback());
                //libPlayer.SmartPlayerSetSEIDataCallback(playerHandle, new SEIDataCallback());

                libPlayer.SmartPlayerSetAudioOutputType(playerHandle, 0);

                if (isMute) {
                    libPlayer.SmartPlayerSetMute(playerHandle, isMute ? 1
                            : 0);
                }

                if (isHardwareDecoder) {
                    Log.i(TAG, "check isHardwareDecoder: "
                            + isHardwareDecoder);

                    int hwChecking = libPlayer
                            .SetSmartPlayerVideoHWDecoder(playerHandle,
                                    isHardwareDecoder ? 1 : 0);

                    Log.i(TAG, "[daniulive] hwChecking: " + hwChecking);
                }

                libPlayer.SmartPlayerSetLowLatencyMode(playerHandle, isLowLatency ? 1
                        : 0);

                libPlayer.SmartPlayerSetFlipVertical(playerHandle, is_flip_vertical ? 1 : 0);

                libPlayer.SmartPlayerSetFlipHorizontal(playerHandle, is_flip_horizontal ? 1 : 0);

                libPlayer.SmartPlayerSetRotation(playerHandle, rotate_degrees);

                int iPlaybackRet = libPlayer
                        .SmartPlayerStartPlay(playerHandle);

                if (iPlaybackRet != 0) {
                    Log.e(TAG, "StartPlayback strem failed..");
                    return;
                }

                isPlaying = true;
                Log.i(TAG, "Start playback stream--");

            //    easyPlayerClient.play(url);
            } else {
//            client.play(BuildConfig.RTSP_URL);
            }
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        easyPlayerClient.stop();
    }
    @Override
    public void onResume() {
        super.onResume();
        easyPlayerClient.resume();
    }

    @Override
    public void onDestroy() {
        getDefault().unregister(this);
        super.onDestroy();
    }


}
